package com.winsdom.valid;

import com.winsdom.anno.ValidExpenditure;
import com.winsdom.entity.Expenditure;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

@Component
public class ExpenditureValidator implements ConstraintValidator<ValidExpenditure, Expenditure> {

    @Override
    public boolean isValid(Expenditure expenditure, ConstraintValidatorContext context) {
        Integer nature = expenditure.getNature();

        if (nature == null) {
            return true; // 基础校验已处理null情况
        }

        boolean valid = true;
        context.disableDefaultConstraintViolation();

        switch (nature) {
            case 2: // 三表类计费
                if (expenditure.getChargingType() == null || expenditure.getChargingType().isEmpty()) {
                    context.buildConstraintViolationWithTemplate("三表类计费必须设置计费类型")
                            .addPropertyNode("chargingType")
                            .addConstraintViolation();
                    valid = false;
                }
                break;

            case 4: // 保证金计费
                if (expenditure.getBondType() == null || expenditure.getBondType().isEmpty()) {
                    context.buildConstraintViolationWithTemplate("保证金计费必须设置保证金类型")
                            .addPropertyNode("bondType")
                            .addConstraintViolation();
                    valid = false;
                }
                break;

            case 5: // 预存计费
                if (expenditure.getPrestoreAccount() == null || expenditure.getPrestoreAccount().isEmpty()) {
                    context.buildConstraintViolationWithTemplate("预存计费必须设置预存账户")
                            .addPropertyNode("prestoreAccount")
                            .addConstraintViolation();
                    valid = false;
                }
                break;
        }

        return valid;
    }
}